home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / SNIP0492.ARJ / PFOPEN.C < prev    next >
C/C++ Source or Header  |  1992-01-05  |  2KB  |  83 lines

  1. /*
  2.  *  Written and released to the public domain by David Engel.
  3.  *
  4.  *  This function attempts to open a file which may be in any of
  5.  *  several directories.  It is particularly useful for opening
  6.  *  configuration files.  For example, PROG.EXE can easily open
  7.  *  PROG.CFG (which is kept in the same directory) by executing:
  8.  *
  9.  *      cfg_file = pfopen("PROG.CFG", "r", getenv("PATH"));
  10.  *
  11.  *  NULL is returned if the file can't be opened.
  12.  */
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17.  
  18. #ifndef __ZTC__
  19.  #define FILENAME_MAX _MAX_PATH
  20. #endif
  21.  
  22. #ifdef unix
  23.  #define SEP_CHARS ":"
  24. #else
  25.  #define SEP_CHARS ";"
  26. #endif
  27.  
  28. FILE *pfopen(const char *name, const char *mode, const char *dirs)
  29. {
  30.     char *ptr;
  31.     char *tdirs;
  32.     FILE *file = NULL;
  33.  
  34.     if (dirs == NULL || dirs[0] == '\0')
  35.         return NULL;
  36.  
  37.     if ((tdirs = malloc(strlen(dirs)+1)) == NULL)
  38.         return NULL;
  39.  
  40.     strcpy(tdirs, dirs);
  41.  
  42.     for (ptr = strtok(tdirs, SEP_CHARS); file == NULL && ptr != NULL;
  43.         ptr = strtok(NULL, SEP_CHARS))
  44.     {
  45.         size_t len;
  46.         char work[FILENAME_MAX];
  47.  
  48.         strcpy(work, ptr);
  49.         len = strlen(work);
  50.         if (len && work[len-1] != '/' && work[len-1] != '\\')
  51.             strcat(work, "/");
  52.         strcat(work, name);
  53.  
  54.         file = fopen(work, mode);
  55.     }
  56.  
  57.     free(tdirs);
  58.  
  59.     return file;
  60. }
  61.  
  62. #ifdef TEST
  63.  
  64. int main(int argc, char **argv)
  65. {
  66.     FILE *file;
  67.  
  68.     if (argc != 4)
  69.     {
  70.         fprintf(stderr, "usage: pfopen name mode dirs\n");
  71.         exit(1);
  72.     }
  73.  
  74.     file = pfopen(argv[1], argv[2], argv[3]);
  75.  
  76.     printf("%s \"%s\" with mode \"%s\"\n", (file == NULL) ?
  77.         "Could not open" : "Opened", argv[1], argv[2]);
  78.  
  79.     return 0;
  80. }
  81.  
  82. #endif
  83.